<!-- 元数据编辑对话框 -->
<template>
  <CommonDialog
    v-model="visible"
    :loading="loading"
    :title="`${dataId ? '编辑' : '新建'}知识条目`"
    :width="600"
    @submit="submit"
    @cancel="cancel"
  >
    <Form ref="formEl" :model="formData" :rules="rules" :label-width="100">
      <FormItem label="标题" prop="title">
        <Input v-model="formData.title" placeholder="请输入标题" />
      </FormItem>

      <FormItem label="有效期">
        <DatePicker
          v-model="formData.begintime"
          type="datetimerange"
          placeholder="请选择有效期"
          @on-change="dateChange"
        />
      </FormItem>

      <FormItem label="热点问题" prop="top">
        <ul class="hotspot-question">
          <li v-for="(item, index) in formData.silimar" :key="index">
            <Input v-model="item.value" placeholder="请输入标题" />
            <Icon
              type="ios-close-circle"
              color="#ff0000"
              size="24"
              @click="delQuestion(index)"
            />
          </li>
        </ul>

        <Button type="primary" class="question-btn" @click="questionAdd">添加</Button>
      </FormItem>

      <FormItem label="热点问题" prop="top">
        <RadioGroup v-model="formData.top">
          <Radio :label="true">是(出现在访客对话页面右侧热门问题)</Radio>
          <Radio :label="false">否</Radio>
        </RadioGroup>
      </FormItem>

      <FormItem label="回复内容" prop="content">
        <Input
          v-model="formData.content"
          type="textarea"
          :rows="4"
          placeholder="请输入标签回复内容"
        />
      </FormItem>

      <FormItem label="知识摘要" prop="summary">
        <Input v-model="formData.summary" placeholder="请输入知识摘要" />
      </FormItem>

      <FormItem label="关键字" prop="keyword">
        <Input v-model="formData.keyword" placeholder="请输入关键字" />
      </FormItem>
    </Form>
  </CommonDialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { Message } from 'view-ui-plus'

import { faq } from '@/api/modules/knowledgeBase'
import { modelManage, dataSource } from '@/api/modules/modelSetting'

import { MODELTYPE_OPTIONS } from '@/util/conf'

import { listToTree } from '@/util/index'
import { ElTreeSelect } from 'element-plus'

const emit = defineEmits(['cancel', 'submit'])

const props = defineProps({
  currentTypeData: {
    type: Object,
    default: () => {
      return {}
    }
  },
  knowDetails: Object
})

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

const dataId = ref(undefined)
// 表单元素ref
const formEl = ref(null)

const getSilimarOptions = () => {
  return {
    value: ''
  }
}
// 表单数据
const formData = ref({
  title: '',
  top: true,
  silimar: [getSilimarOptions()],
  begintime: [],
  content: '',
  summary: '',
  keyword: ''
})

// 表单校验条件
const rules = ref({
  title: [{ required: true, message: '请填写标题', trigger: 'blur' }]
})

const dateChange = (data) => {
  formData.value.begintime = data.map((item) => {
    const date = new Date(item)

    return date.getTime()
  })
}

const questionAdd = () => {
  formData.value.silimar.push(getSilimarOptions())
}

const delQuestion = (index) => {
  if(formData.value.silimar.length === 1) return

  formData.value.silimar.splice(index, 1)
}

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    const params = {
      ...formData.value,
      begintime: formData.value.begintime[0],
      endtime: formData.value.begintime[1],
      silimar: formData.value.silimar.map(item=>item.value),
      id: dataId.value,
      aiid: props.knowDetails.aiknowledgebody?.aimodel,
      cate: props.currentTypeData.id || undefined
    }

    await faq[dataId.value ? 'edit' : 'add']({
      data: params
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

const getDetailData = () => {
  loading.value = true

  faq
    .detail({
      data: {
        id: dataId.value
      }
    })
    .then(({ data }) => {
      for (const key in formData.value) {
        if(key === 'begintime') {
          formData.value[key] = [data.begintime, data.endtime]
          continue
        }

        if(key === 'silimar') {
          formData.value[key] = data.silimar.map(item=>({
            value: item
          }))
          continue
        }

        formData.value[key] = data[key]
      }
      console.log(formData.value)
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 初始化对话框
 */
const initDialog = (id) => {
  // 显示对话框
  visible.value = true

  dataId.value = id

  if (id) {
    getDetailData()
  }
}

defineExpose({
  initDialog
})
</script>

<style scoped lang="scss">
.flex-form {
  display: flex;
}
.ivu-input-wrapper,
.ivu-select,
.el-select,
.ivu-date-picker {
  width: 380px;
}
::deep(.ivu-form-item-label) {
  text-align: right;
}

.hotspot-question {
  max-height: 300px;
  overflow-y: auto;
  li {
    display: flex;
    align-items: center;
    &:nth-child(n + 2) {
      margin-top: 8px;
    }
    .ivu-icon {
      cursor: pointer;
      transition: all 0.2s;
      &:hover {
        opacity: 0.7;
      }
    }
  }
}
.question-btn {
  margin-top: 8px;
}
</style>
